package com.example.springsecuritydemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.springsecuritydemo.mapper.RoleMapper;
import com.example.springsecuritydemo.model.Role;
import com.example.springsecuritydemo.model.Users;
import com.example.springsecuritydemo.service.RoleService;
import com.example.springsecuritydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 用户登录
     *
     * @param s 获取到的UserName,
     * @return user 返回的是org.springframework.security.core.userdetails.User;
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (s == null || "".equals("s")) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询对象
        LambdaQueryWrapper<Users> usersWrapper = Wrappers.lambdaQuery(Users.class).eq(Users::getUserName, s);
        Users user = userService.getOne(usersWrapper);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //根据userId获取Role对象
        LambdaQueryWrapper<Role> roleWrapper = Wrappers.lambdaQuery(Role.class).eq(Role::getUserId, user.getUserId());
        List<Role> roles = roleMapper.selectList(roleWrapper);
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        //这里没有对用户密码进行判断，将数据库中查到的密码封装到了对象中，在WebSecurityConfig中configure()方法中，User进行了验证，
        //前端传递的密码是明文，数据中存的是暗文,需要对前端传递的密码加密，进行验证,加密方法是new BCryptPasswordEncoder().encode("pwd")
        return new User(user.getUserName(), user.getUserPwd(), authorities);
    }
}